package com.jcfk.system.controller;

import com.jcfk.common.core.context.SpringContextUtils;
import com.jcfk.system.service.WebSocketMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * WebSocket消息
 *
 */
@Slf4j
@ServerEndpoint(value = "/webSocket/sysWebMessage")
@Component
public class WebSocketMessageController {

    /**
     * 通知socket服务
     */
    @Autowired
    private WebSocketMessageService webSocketMessageService = SpringContextUtils.getBean(WebSocketMessageService.class);

    /**
     * 记录当前在线连接数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        webSocketMessageService.onOpen(session);//建立连接
        onlineCount.incrementAndGet(); // 在线数加1
        log.info("有新连接加入：session[{}]，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        webSocketMessageService.onClose(session);//关闭连接
        onlineCount.decrementAndGet(); // 在线数减1
        log.info("有一连接关闭：session[{}]，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        // log.info("收到session[{}]的消息:{}", session.getId(), message);
        webSocketMessageService.onMessage(message,session);
        //this.sendMessage("Hello, " + message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("session["+session.getId()+"]出现异常",error);
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
        try {
            // log.info("给session[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败：{}", e);
        }
    }
}
